package com.lyn.tool.mvp.view.adapter;

import android.view.View;
import android.view.ViewGroup;
import androidx.viewbinding.ViewBinding;
import java.util.LinkedList;
import java.util.List;

public abstract class BaseAdapter<T,V extends ViewBinding> extends android.widget.BaseAdapter {

    private final List<T> data;

    public BaseAdapter() {
        data = new LinkedList<>();
    }

    public BaseAdapter(List<T> data) {
        this.data = data;
    }

    public void setData(List<T> data) {
        this.data.addAll(data);
        notifyDataSetChanged();
    }
    public void setData(T itemData) {
        this.data.add(itemData);
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        if (data.isEmpty()) {
            return 0;
        }
        return data.size();
    }

    @Override
    public T getItem(int position) {
        if (data.isEmpty()) {
            return null;
        }
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder<V> holder;
        if (convertView==null){
            holder=new ViewHolder<>(getViewBinding());
            convertView=holder.viewBinding.getRoot();
            convertView.setTag(holder);
        }else {
            holder= (ViewHolder<V>) convertView.getTag();
        }
        onViewHolder(holder.viewBinding, data.get(position));
        return convertView;
    }



    protected abstract V getViewBinding();
    protected abstract void onViewHolder(V v,T t);


   protected static class ViewHolder<V> {
       public V viewBinding;

       public ViewHolder(V viewBinding) {
           this.viewBinding = viewBinding;
       }
   }
}
